<!DOCTYPE HTML>
<chat xmlns:th="http://www.thymeleaf.org"
      xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
<head>

    <title>Demo Chat</title>

    <link th:href="@{/static/css/bootstrap.css}" rel="stylesheet">

    <style>
        body {
            padding:20px;
        }
        #console {
            height: 400px;
            overflow: auto;
        }
        .username-msg {color:orange;}
        .connect-msg {color:green;}
        .disconnect-msg {color:red;}
        .send-msg {color:#888}
    </style>
</head>

<body>

<h1>Netty-socketio Demo Chat</h1>
<a th:href="@{/logout}">注销</a>

<br/>

<div id="console" class="well">
</div>

<form class="well form-inline" onsubmit="return false;">
    <input id="msg" class="input-xlarge" type="text" placeholder="Type something..."/>
    <button type="button" onClick="sendMessage()" class="btn" id="send">Send</button>
    <button type="button" onClick="sendDisconnect()" class="btn">Disconnect</button>
</form>

<span style="display: none" id="username" sec:authentication="name"></span>

<script th:src="@{/static/js/socket.io/socket.io.js}"></script>
<script th:src="@{/static/js/moment.min.js}"></script>
<script th:src="@{/static/js/jquery-1.10.1.min.js}"></script>

<script type="text/javascript">

    var username = undefined;

    var socket =  io.connect('https://localhost:8080');

    socket.on('connect', function() {
        output('<span class="connect-msg">Client has connected to the server!</span>');
    });

    socket.on('chatevent', function(data) {
        var index = data.indexOf(':');
        var username = data.substring(0, index);
        var message = index + 1 >= data.length ? "" : data.substring(index + 1);
        output('<span class="username-msg">' + username + '</span> ' + message);
    });

    socket.on('disconnect', function() {
        output('<span class="disconnect-msg">The client has disconnected!</span>');
    });

    function sendDisconnect() {
        socket.disconnect();
    }

    function sendMessage() {
        var message = $('#msg').val();
        $('#msg').val('');
        socket.emit('chatevent', username + ": " + message);
    }

    function output(message) {
        var currentTime = "<span class='time'>" +  moment().format('HH:mm:ss.SSS') + "</span>";
        var element = $("<div>" + currentTime + " " + message + "</div>");
        $('#console').prepend(element);
    }

    $(document).keydown(function(e){
        if(e.keyCode == 13) {
            $('#send').click();
        }
        username = $('#username').text();
    });

</script>
</body>

</chat>
